import { useEffect, useState } from 'react';

import { DeleteOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons';

import { type AccessProtocol } from '@/api/equipmentAccessProtocolApi';
import { TableLocalePresets } from '@/utils/tableUtils';

import styles from './CardList.module.css';

import type { ActionType } from '@ant-design/pro-components';

/**
 * 接入协议卡片列表组件属性
 */
interface AccessProtocolCardListProps {
  /** 表格操作引用 */
  actionRef: React.RefObject<ActionType | null>;
  /** 编辑回调 */
  onEdit: (record: AccessProtocol) => void;
  /** 删除回调 */
  onDelete: (record: AccessProtocol) => void;
  /** 新增回调 */
  onAdd?: () => void;
  /** 数据获取函数 */
  fetchData: (params: Record<string, unknown>) => Promise<any>;
  /** 外部搜索参数，用于触发刷新 */
  searchParams?: Record<string, unknown>;
}

/**
 * 接入协议卡片列表组件
 * 以卡片形式展示接入协议列表，支持编辑、删除、查看详情等操作
 */
const AccessProtocolCardList: React.FC<AccessProtocolCardListProps> = ({
  actionRef,
  onEdit,
  onDelete,
  onAdd,
  fetchData,
  searchParams,
}) => {
  // 列表数据状态
  const [loading, setLoading] = useState(false);
  const [dataSource, setDataSource] = useState<AccessProtocol[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 12,
    total: 0,
  });

  // 详情弹窗状态
  const [detailVisible, setDetailVisible] = useState(false);
  const [currentDetail, setCurrentDetail] = useState<AccessProtocol | null>(null);

  // 设备数据状态
  const [deviceData, setDeviceData] = useState<any[]>([]);
  const [deviceLoading, setDeviceLoading] = useState(false);
  const [devicePagination, setDevicePagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 加载数据
  const loadData = async () => {
    try {
      setLoading(true);
      const result = await fetchData({
        current: pagination.current,
        pageSize: pagination.pageSize,
      });

      if (result.success) {
        setDataSource(result.data || []);
        setPagination(prev => ({
          ...prev,
          total: result.total || 0,
        }));
      }
    } catch (error) {
      console.error('加载数据失败:', error);
      setDataSource([]);
    } finally {
      setLoading(false);
    }
  };

  // 初始化加载
  useEffect(() => {
    loadData();
  }, [pagination.current, pagination.pageSize]);

  // 监听 actionRef 的 reload 方法
  useEffect(() => {
    if (actionRef.current) {
      actionRef.current.reload = async () => {
        await loadData();
      };
    }
  }, [actionRef]);

  // 监听外部搜索参数变化，触发数据刷新
  useEffect(() => {
    if (searchParams) {
      loadData();
    }
  }, [searchParams]);

  // 分页变化处理
  const handlePaginationChange = (page: number, pageSize?: number) => {
    setPagination(prev => ({
      ...prev,
      current: page,
      pageSize: pageSize || prev.pageSize,
    }));
  };

  // 查看详情
  const handleViewDetail = (item: AccessProtocol) => {
    setCurrentDetail(item);
    setDetailVisible(true);
    // 加载设备数据
    loadDeviceData(item.productCode);
  };

  // 加载设备数据
  const loadDeviceData = async (productCode?: string, params?: any) => {
    if (!productCode) return;

    try {
      setDeviceLoading(true);
      // 动态导入API函数
      const { deviceManagerListApi } = await import('@/api/deviceManagerApi');

      const requestParams = {
        productCode,
        current: params?.current || devicePagination.current,
        size: params?.pageSize || devicePagination.pageSize,
        ...params,
      };

      const res = await deviceManagerListApi(requestParams);
      if (res.success) {
        const responseData = res.data;
        setDeviceData(responseData?.records ?? []);
        setDevicePagination(prev => ({
          ...prev,
          current: requestParams.current,
          pageSize: requestParams.size,
          total: responseData?.total ?? 0,
        }));
      }
    } catch (error) {
      console.error('获取设备数据失败:', error);
      window.$message.error('获取设备数据失败');
    } finally {
      setDeviceLoading(false);
    }
  };

  // 设备表格分页处理
  const handleDevicePaginationChange = (page: number, pageSize?: number) => {
    if (currentDetail?.productCode) {
      loadDeviceData(currentDetail.productCode, {
        current: page,
        pageSize: pageSize || devicePagination.pageSize,
      });
    }
  };

  // 渲染值的辅助函数
  const renderValue = (value: any, defaultText = '暂无数据') => {
    if (value === null || value === undefined || value === '') {
      return defaultText;
    }
    return value;
  };

  // 渲染新增实例卡片
  const renderAddCard = () => (
    <ACol xs={24} sm={12} md={8} lg={6} xl={6} key="add-card">
      <ACard
        hoverable // cspell:disable-line
        className="cursor-pointer"
        style={{
          height: '200px',
          borderStyle: 'dashed',
          borderColor: '#d9d9d9',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
        }}
        styles={{
          body: {
            padding: '24px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            height: '100%',
          },
        }}
        onClick={() => {
          onAdd?.();
        }}
      >
        <div className="text-center">
          <PlusOutlined style={{ fontSize: '48px', color: '#d9d9d9', marginBottom: '16px' }} />
          <div style={{ color: '#999', fontSize: '16px', fontWeight: 500 }}>新增实例</div>
        </div>
      </ACard>
    </ACol>
  );

  // 渲染实例卡片
  const renderInstanceCard = (item: AccessProtocol) => (
    <ACol xs={24} sm={12} md={8} lg={6} xl={6} key={item.id}>
      <div className={styles.cardContainer}>
        <ACard
          hoverable // cspell:disable-line
          style={{ height: '100%' }}
          styles={{ body: { padding: '8px 16px', height: '100%' } }}
        >
          {/* 悬浮操作按钮 */}
          <div className={styles.cardActions}>
            <AButton
              type="text"
              size="small"
              icon={<span style={{ fontSize: '14px' }}>👁</span>}
              onClick={e => {
                e.stopPropagation();
                handleViewDetail(item);
              }}
              className={`${styles.actionButton} ${styles.viewButton}`}
              title="查看详情"
            />
            <AButton
              type="text"
              size="small"
              icon={<EditOutlined />}
              onClick={e => {
                e.stopPropagation();
                onEdit(item);
              }}
              className={`${styles.actionButton} ${styles.editButton}`}
            />
            <AButton
              type="text"
              size="small"
              icon={<DeleteOutlined />}
              onClick={e => {
                e.stopPropagation();
                onDelete(item);
              }}
              className={`${styles.actionButton} ${styles.deleteButton}`}
            />
          </div>

          <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
            {/* 标题区域 */}
            <div style={{ marginBottom: '16px' }}>
              <h4
                style={{
                  fontSize: '16px',
                  fontWeight: 600,
                  marginBottom: '8px',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                }}
                title={item.name}
              >
                {item.name || '未命名实例'}
              </h4>
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <ABadge
                  status={item.status === 1 ? 'success' : 'error'}
                  text={item.status === 1 ? '在线' : '离线'}
                  style={{ fontSize: '14px' }}
                />
              </div>
            </div>

            {/* 内容区域 */}
            <div style={{ flex: 1, fontSize: '14px', color: '#666' }}>
              <div style={{ marginBottom: '8px' }}>
                <span style={{ color: '#999' }}>当前接入设备数：</span>
                <span style={{ fontWeight: 500, color: '#333' }}>{item.deviceCount || 0}</span>
              </div>

              <div>
                <div style={{ color: '#999', marginBottom: '4px' }}>实例描述：</div>
                <div
                  style={{
                    fontSize: '13px',
                    color: '#666',
                    lineHeight: '1.4',
                    overflow: 'hidden',
                    display: '-webkit-box',
                    WebkitLineClamp: 2,
                    WebkitBoxOrient: 'vertical',
                  }}
                  title={item.remark}
                >
                  {item.remark}
                </div>
              </div>
            </div>
          </div>
        </ACard>
      </div>
    </ACol>
  );

  return (
    <div>
      <ASpin spinning={loading}>
        <ARow gutter={[24, 24]}>
          {/* 新增实例卡片 */}
          {renderAddCard()}

          {/* 实例列表卡片 */}
          {dataSource.map(item => renderInstanceCard(item))}
        </ARow>
      </ASpin>

      {/* 分页 */}
      {pagination.total > 0 && (
        <div className="flex justify-end py-4">
          <APagination
            current={pagination.current}
            pageSize={pagination.pageSize}
            total={pagination.total}
            showSizeChanger
            showQuickJumper
            showTotal={(total, range) =>
              `共 ${total} 项数据，当前显示第 ${range[0]}-${range[1]} 项`
            }
            onChange={handlePaginationChange}
            onShowSizeChange={handlePaginationChange}
          />
        </div>
      )}

      {/* 详情抽屉 */}
      <ADrawer
        title="实例详情"
        open={detailVisible}
        onClose={() => {
          setDetailVisible(false);
          setDeviceData([]);
          setDevicePagination({ current: 1, pageSize: 10, total: 0 });
        }}
        width={800}
        footer={
          <div className="flex justify-end">
            <AButton
              onClick={() => {
                setDetailVisible(false);
                setDeviceData([]);
                setDevicePagination({ current: 1, pageSize: 10, total: 0 });
              }}
            >
              关闭
            </AButton>
          </div>
        }
      >
        {currentDetail && (
          <div style={{ padding: '16px 0' }}>
            {/* 基本信息 */}
            <div style={{ marginBottom: '24px' }}>
              <ADescriptions title="基本信息" bordered size="small" column={2}>
                <ADescriptions.Item label="服务状态">
                  <ABadge
                    status={currentDetail.status === 1 ? 'success' : 'error'}
                    text={currentDetail.status === 1 ? '在线' : '离线'}
                  />
                </ADescriptions.Item>

                <ADescriptions.Item label="当前接入设备数">
                  {renderValue(currentDetail.deviceCount, '0')}
                </ADescriptions.Item>

                <ADescriptions.Item label="绑定产品">
                  {renderValue(currentDetail.productName)}
                </ADescriptions.Item>

                <ADescriptions.Item label="创建时间">
                  {renderValue(currentDetail.createTime)}
                </ADescriptions.Item>

                <ADescriptions.Item label="Key" span={2}>
                  <span
                    style={{ fontFamily: 'monospace', fontSize: '12px', wordBreak: 'break-all' }}
                  >
                    {renderValue(currentDetail.keyInfo)}
                  </span>
                </ADescriptions.Item>

                <ADescriptions.Item label="Username">
                  <span style={{ fontFamily: 'monospace', fontSize: '12px' }}>
                    {renderValue(currentDetail.mqttUserName)}
                  </span>
                </ADescriptions.Item>

                <ADescriptions.Item label="ClientID">
                  <span style={{ fontFamily: 'monospace', fontSize: '12px' }}>
                    {renderValue(currentDetail.mqttClientId)}
                  </span>
                </ADescriptions.Item>

                <ADescriptions.Item label="产品描述" span={2}>
                  {renderValue(currentDetail.remark)}
                </ADescriptions.Item>
              </ADescriptions>
            </div>

            {/* 设备管理表格 */}
            <ACard title="设备管理" size="small">
              <div style={{ minHeight: '300px' }}>
                <ATable
                  columns={[
                    {
                      title: '设备code',
                      dataIndex: 'code',
                      key: 'code',
                      render: (text: string) => renderValue(text),
                    },
                    {
                      title: '所属产品',
                      dataIndex: 'productName',
                      key: 'productName',
                      render: (text: string) => renderValue(text),
                    },
                    {
                      title: 'IMEI',
                      dataIndex: 'imei',
                      key: 'imei',
                      render: (text: string) => renderValue(text),
                    },
                    {
                      title: '添加时间',
                      dataIndex: 'createTime',
                      key: 'createTime',
                      render: (text: string) => renderValue(text),
                    },
                    {
                      title: '最近在线时间',
                      dataIndex: 'latestOnlineTime',
                      key: 'latestOnlineTime',
                      render: (text: string) => renderValue(text),
                    },
                    {
                      title: '操作',
                      key: 'action',
                      width: 180,
                      render: () => (
                        <ASpace size="small">
                          <AButton
                            type="link"
                            size="small"
                            onClick={() => window.$message.warning('开发中...')}
                          >
                            查看
                          </AButton>
                          <AButton
                            type="link"
                            size="small"
                            onClick={() => window.$message.warning('开发中...')}
                          >
                            编辑
                          </AButton>
                          <AButton
                            type="link"
                            size="small"
                            danger
                            onClick={() => window.$message.warning('开发中...')}
                          >
                            删除
                          </AButton>
                        </ASpace>
                      ),
                    },
                  ]}
                  dataSource={deviceData}
                  loading={deviceLoading}
                  size="small"
                  pagination={{
                    current: devicePagination.current,
                    pageSize: devicePagination.pageSize,
                    total: devicePagination.total,
                    showSizeChanger: true,
                    showQuickJumper: true,
                    showTotal: (total, range) =>
                      `共 ${total} 项数据，当前显示第 ${range[0]}-${range[1]} 项`,
                    onChange: handleDevicePaginationChange,
                    onShowSizeChange: handleDevicePaginationChange,
                  }}
                  locale={TableLocalePresets.product()}
                />
              </div>
            </ACard>
          </div>
        )}
      </ADrawer>
    </div>
  );
};

export default AccessProtocolCardList;
